package cn.wolfcode.controller;

import cn.wolfcode.domain.*;
import cn.wolfcode.query.EmployeeQueryObject;
import cn.wolfcode.result.JsonResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeRoleService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.service.impl.PermissionService;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IEmployeeRoleService employeeRoleService;

    @Autowired
    private PermissionService permissionService;

    //@RequiredPermission(name = "员工页面",experssion = "employee:list")
    //@RequiresPermissions(value={"employee:list","员工页面"},logical = Logical.OR)
    /*@RequestMapping("/list")
    public String list(@ModelAttribute("qo") EmployeeQueryObject qo, Model model) {
        PageInfo<Employee> pageInfo = employeeService.list(qo);
        model.addAttribute("result", pageInfo);
        List<Department> deptlist = departmentService.selectAll();
        model.addAttribute("deptList", deptlist);
        return "employee/list";
    }*/

    //@RequiredPermission(name = "员工删除",experssion = "employee:delete")
    @RequiresPermissions(value = {"employee:delete", "员工删除"}, logical = Logical.OR)
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        employeeService.deleteByPrimaryKey(id);
        return JsonResult.success(null);
    }

    //@RequiredPermission(name = "员工新增/编辑",experssion = "department:saveOrUpdate")
    /*@RequiresPermissions(value = {"employee:saveOrUpdate", "员工新增/编辑"}, logical = Logical.OR)
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        //通过获取参数对象中的ID 来判断是新增还是编辑
        List<Department> departments = departmentService.selectAll();
        model.addAttribute("deptList", departments);
        List<Role> roles = roleService.selectAll();
        model.addAttribute("roleList", roles);
        if (id == null) {
            //新增
        } else {
            //编辑
            Employee employee = employeeService.selectByPrimaryKey(id);
            model.addAttribute("current", employee);
            List<Role> roleList = roleService.selectByEmployeeId(id);
            model.addAttribute("selfRoles", roleList);
        }
        return "employee/input";
    }*/

    //保存 编辑   为了满足身兼数职 接收的是一个数组
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee employee, Long[] ids) {
        //通过获取参数对象中的ID 来判断是新增还是编辑
        if (employee.getId() == null) {
            //插入员工信息
            employeeService.insert(employee);
            //同时在角色表中查询一个该员工的角色身份信息
            Long employeeid = employee.getId();
            if (ids != null) {
                for (Long id : ids) {
                    employeeRoleService.insert(new EmployeeRole(employeeid, id));
                }
            }
        } else {
            employeeService.updateByPrimaryKey(employee);
            //删除原有角色
            employeeRoleService.deleteByEmployeeId(employee.getId());
            //插入新角色
            if (ids != null) {
                for (Long id : ids) {
                    employeeRoleService.insert(new EmployeeRole(employee.getId(), id));
                }
            }
        }
        return "redirect:/employee/list";
    }

    @RequestMapping("/batchdelete")
    @ResponseBody
    public JsonResult batchdelete(Long[] ids) {
        employeeService.batchDeleteByEmployeeIds(ids);
        employeeRoleService.batchDeleteByEmployeeIds(ids);
        return JsonResult.success(null);
    }

    /*@RequestMapping("/login")
    @ResponseBody
    public JsonResult login(Employee employee, HttpSession session) {
        Employee e = employeeService.selectByUsername(employee.getUsername());
        if (e==null){
            return JsonResult.error("用户名不存在");
        }else{
            if (e.getPassword().equals(employee.getPassword())){
                //登陆成功
                //1.查询权限
                List<Permission> permissions = permissionService.selectByEmployeeId(e.getId());
                //2.把权限存入SESSION
                session.setAttribute("currentuser",e.getUsername());
                session.setAttribute("userpermission",permissions);
                //3.返回结果 JSONRESULT
                return JsonResult.success(null);
            }else {
                return JsonResult.error("密码错误");
            }
        }

    }*/

    /*@RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password) {

        try {
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
            SecurityUtils.getSubject().login(usernamePasswordToken);
            return JsonResult.success(null);
        }catch (UnknownAccountException u) {
            u.printStackTrace();
            return JsonResult.error("用户名错误！");
        }catch (IncorrectCredentialsException i){
            i.printStackTrace();
            return JsonResult.error("密码错误！");
        }

    }*/

    //导出
    @RequestMapping("/export")
    public void export(HttpServletResponse resp) throws IOException {
        //提交一个数据保存到xls的请求  JAVA 操作 XLS 文件
        //在响应头信息中要设定保存的文件名 保存类型
        resp.setHeader("Content-Disposition","attachment;filename=employee.xls");
        //需要操作XLS   WorkBook
        //获取数据
        Workbook workbook = employeeService.getWorkbook();
        //保存 生成文件
        workbook.write(resp.getOutputStream());
    }

    //导入
    @RequestMapping("/export_model")
    public void export_model(HttpServletResponse resp) throws IOException {

        resp.setHeader("Content-Disposition","attachment;filename=employee.xls");
        Workbook workbook = employeeService.getWorkbook_model();
        workbook.write(resp.getOutputStream());
    }

    //导入模板
    @RequestMapping("/importXls")
    public String importXls(MultipartFile file) throws IOException {
       employeeService.importXls(file);
       return "redirect:/employee/list";
    }



    @RequestMapping("/checkName")
    @ResponseBody
    public Map checkName(String username) throws IOException {
        //valid  true(代表验证通过 可以注册) false(验证不通过 不可以注册)
        Employee employee = employeeService.selectByUsername(username);
        Map<String,Boolean> map = new HashMap<>();
        if (employee==null){
            map.put("valid",true);
        }else{
            map.put("valid",false);
        }
        return map;
    }

}
